<script setup>
import { ref, onMounted } from 'vue';
import { Plus, Delete, Edit } from '@element-plus/icons-vue'; // 引入编辑图标
import { useRouter } from "vue-router";
import { getproductsList, deleteProduct } from "@/apis/product";
import { ElMessage } from 'element-plus';

const router = useRouter();
const productList = ref([]);
const pageInfo = ref({
  current: 1,
  size: 8,
  total: 0
});

const pushToPath = (path) => {
  router.push(path);
};

const getProducts = async (c = 1, t = 8) => {
  try {
    const res = await getproductsList(c, t);
    productList.value = res.records;
    pageInfo.value.total = parseInt(res.total, 10);
    pageInfo.value.size = res.size;
    pageInfo.value.current = res.current;
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败');
  }
};

const handlePageChange = (current) => {
  pageInfo.value.current = current;
  getProducts(current);
};

const handleDeleteProduct = async (id) => {
  try {
    const res = await deleteProduct(id); // 调用删除商品接口（硬删除）
    if (res.success) {
      getProducts(pageInfo.value.current); // 重新加载商品列表
      ElMessage.success("删除成功！");
    } else {
      ElMessage.error("删除失败！");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("删除出错，请稍后重试！");
  }
};

onMounted(() => {
  getProducts();
});
</script>

<template>
  <el-row>
    <el-button :icon="Plus" @click="pushToPath('/admin/product/add')">新增商品</el-button>
  </el-row>
  <el-row>
    <el-table :data="productList" style="width: 100%">
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="subTitle" label="描述" />
      <el-table-column prop="mainImage" label="封面">
        <template #default="scope">
          <img :src="'/api/images/' + scope.row.mainImage" alt="" style="width: 100px; height: 100px;" />
        </template>
      </el-table-column>
      <el-table-column prop="categoryId" label="分类ID" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="stock" label="库存" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="primary" icon="Edit" @click="pushToPath(`/admin/product/edit/${scope.row.id}`)">
            编辑
          </el-button>
          <el-button size="small" type="danger" icon="Delete" @click="handleDeleteProduct(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div class="product-list-pagination">
      <el-pagination
          v-model:currentPage="pageInfo.current"
          :page-size="pageInfo.size"
          :total="pageInfo.total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </el-row>
</template>

<style scoped>
.product-list-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
